package com.example.player.web;


import com.example.player.ex.ServiceException;

/**
 * 自定义的返回前端数据类型JsonResult
 * @author fendou2021
 * @create 2022-04-16 10:19
 */
public class JsonResult<T> {

    //状态返回码
    private Integer state;

    //消息
    private String message;

    //返回数据类型
    private T data;

    private JsonResult() {
    }

    public static JsonResult<Void> ok() {
        return ok(null);
    }

    public static <T> JsonResult<T> ok(T data) {
        JsonResult<T> jsonResult = new JsonResult<>();
        jsonResult.state = State.OK.getValue();
        jsonResult.data = data;
        return jsonResult;
    }

    public static JsonResult<Void> fail(State state, String message) {
        JsonResult<Void> jsonResult = new JsonResult<>();
        jsonResult.state = state.getValue();
        jsonResult.message = message;
        return jsonResult;
    }

    public static JsonResult<Void> fail(ServiceException e) {
        return fail(e.getState(), e.getMessage());
    }

    public enum State {

        OK(200),
        REDIRECT(302),
        BAD_REQUEST(400),
        UNAUTHORIZED(401),
        FORBIDDEN(403),
        NOT_FOUND(404),
        METHOD_NOT_ALLOWED(405),
        CONFLICTED(409),
        SERVER_ERROR(500),
        SERVICE_UNAVAILABLE(503),
        OTHER_EXCEPTION(504);

        Integer value;

        State(Integer value) {
            this.value = value;
        }

        public Integer getValue() {
            return value;
        }
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "JsonResult{" +
                "state=" + state +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}
